﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using TaobalLibrary.Requests;

namespace TaobaoLibrary
{
    public class Shop
    {
        protected Shop(string name)
        {
            Name = name;
        }

        public string Name { get; protected set; }

        public IList<Product> GetProducts()
        {
            List<Product> products = new List<Product>();

            HtmlNode nextPageNode = null;
            do
            {
                string pageUri = null;
                if (nextPageNode != null)
                {
                    pageUri = nextPageNode.Attributes["href"].Value;
                }
                else
                {
                    pageUri = "http://" + Name + ".taobao.com/?search=y";
                }

                string html = Requests.GetText(pageUri);
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(html);

                foreach (HtmlNode productItem in doc.DocumentNode.SelectNodes("//div[@class='item']"))
                {
                    Product product = new Product(productItem, this);
                    products.Add(product);
                }
                nextPageNode = doc.DocumentNode.SelectSingleNode("//a[@class='J_SearchAsync next']");
            } while (nextPageNode != null);

            return products;
        }

        public static Shop GetShop(string name)
        {
            return new Shop(name);
        }
    }
}
